/***************************************************************************
 *   Copyright (C) 2008 by Hector Francisco Hernandez                      *
 *   hectorfh@gmail.com                                                    *
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 *   This program is distributed in the hope that it will be useful,       *
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
 *   GNU General Public License for more details.                          *
 *                                                                         *
 *   You should have received a copy of the GNU General Public License     *
 *   along with this program; if not, write to the                         *
 *   Free Software Foundation, Inc.,                                       *
 *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
 ***************************************************************************/

#include "car_row.h"
#include "car.h"
#include <stdlib.h>
#include <time.h>

#define MAX_NCARS 16
#define MAX_CAR_SEP 10
#define MIN_CAR_SEP 4

struct car_row
{
  struct car *cars[MAX_NCARS];
  int ncars;
  int x, y;
  int length;
  WINDOW *window;
};

struct car_row *car_row_create(WINDOW *window, int x, int y, int length, int dir)
{
  int x1 = x;

  struct car_row *car_row = (struct car_row *) malloc(sizeof(struct car_row));

  car_row->ncars = 0;

  x1 += (float) rand() / RAND_MAX * 5;

  while (x1 < x + length - MAX_CAR_LEN && car_row->ncars < MAX_NCARS - 1) {
    struct car *car = car_create(window, x1, y, dir);
    car_row->cars[car_row->ncars++] = car;
    x1 += car_length(car);
    x1 += MIN_CAR_SEP + (float) rand() / RAND_MAX * (MAX_CAR_SEP - MIN_CAR_SEP + 1);
  }

  car_row->x = x;
  car_row->y = y;
  car_row->length = length;
  car_row->window = window;

  return car_row;
}

void car_row_draw(struct car_row *car_row)
{
  int i;

  for (i = 0; i < car_row->ncars; i++) {
    car_draw(car_row->cars[i]);
  }
}

int car_row_isin(struct car_row *car_row, int x, int y)
{
//  return y == car->y && x >= car->x && x <= car->x + car->length;
  return 0;
}

void car_row_move(struct car_row *car_row)
{
  int i;

  for (i = 0; i < car_row->ncars; i++) {
    car_move(car_row->cars[i]);
  }
}
